package com.chat.view;

import com.chat.common.User;
import com.chat.service.CheckEmail;
import com.chat.service.CheckSecurityCode;
import com.chat.service.EmailService;
import com.chat.service.UserClientService;
import com.chat.utils.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.commons.lang.RandomStringUtils;
import javax.swing.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Objects;

public class RegisterController {
    public RadioButton malebutton;
    public RadioButton femalebutton;
    public DatePicker borndate;
    public Text yanzheng;
    @FXML
    private Button returnbutton;//返回按钮
    @FXML
    private Button sendbutton;//发送邮箱验证码按钮
     @FXML
     private TextField nicknameTextField;//昵称输入框
     @FXML
     private TextField passwordTextField;//密码输入框
     @FXML
     private TextField confirmpasswordTextField;//确认密码输入框
    @FXML
    private TextField mailboxTextField;//邮箱输入框
    @FXML
    private TextField securitycodeTextField;//验证码输入框
     @FXML
     private Label passwordlabel;//密码输入框提示
    @FXML
    private Label confirmpasswordlabel;//确认密码框提示
    @FXML
    private Label securitycodelabel;//验证码输入框提示
    @FXML
    private Label mailboxlabel;//邮箱输入框提示
    @FXML
    private Label nicknamelabel;//昵称输入框提示
    @FXML
    private Label sexlabel;//性别输入框提示
    @FXML
    private Label registerlabel;//注册成功提示
    @FXML
    private Label usernamelabel;
    public String content;//邮箱验证码
    public String Sex;//保存性别
    public String Borndate;//保存生日
    public String Password;//保存加密之后的密码
    public int flag=0;
    public void initialize() {
           malebutton.setSelected(true);
           yanzheng.setText("点击发送验证码");
          java.util.Date date=new java.util.Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        borndate.setValue(LocalDate.parse(dateFormat.format(date)));
    }
    public void returnbuttonOnAction(ActionEvent event){//返回按钮
        Stage stage=(Stage) returnbutton.getScene().getWindow();
        stage.close();
        try {
            FXMLLoader fxmlLoader = new FXMLLoader();
            fxmlLoader.setLocation(getClass().getResource("login.fxml"));
            Parent root = fxmlLoader.load();
            Stage loginstage=new Stage();
            Scene scene = new Scene(root, 600, 400);
            loginstage.initStyle(StageStyle.TRANSPARENT);
            MouseFollow in = new MouseFollow(root, loginstage);
            loginstage.setScene(scene);
            loginstage.show();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void registerbuttonOnAction(ActionEvent event){//登录按钮的点击事件
           flag=1;
//           if(nicknameTextField.getText().toString().matches("[a-zA-Z]{2,15}"))//判断昵称的格式是否正确
//           {   flag++;
//               nicknamelabel.setText("格式正确！");
//           }
//           else{
//               nicknamelabel.setText("昵称必须为英文\n并且数量在2-15\n之间！");
//           }
            Borndate=borndate.getValue().toString();
           if(malebutton.isSelected()==true)
                Sex="male";
           else Sex="female";
        if(passwordTextField.getText().toString().matches("^[A-Za-z0-9]+${6,15}"))
        {    flag++;
            passwordlabel.setText("格式正确！");
            Md5 k=new Md5();
            Password=k.digest(passwordTextField.getText().toString());
        }
        else passwordlabel.setText("密码可以为字母\n和数字，数量在\n6-15之间！");

       if(passwordTextField.getText().toString().equals(confirmpasswordTextField.getText().toString())&&confirmpasswordTextField.getText().isEmpty()!=true){
            confirmpasswordlabel.setText("格式正确!");
            flag++;

        }
       else if(confirmpasswordTextField.getText().isEmpty()==true){
              confirmpasswordlabel.setText("格式错误！");
       }
       else confirmpasswordlabel.setText("两次密码不一致！");
         CheckSecurityCode csc=new CheckSecurityCode();
        if(csc.check(securitycodeTextField.getText(),mailboxTextField.getText()))
        {     flag++;
               securitycodelabel.setText("验证码正确！");
        }
        else{
              securitycodelabel.setText("验证码错误！");
        }
        if(mailboxTextField.getText().isEmpty()==true)
            mailboxlabel.setText("邮箱无效！");

        if(flag==4) {
            registerlabel.setText("注册成功!");
            try {
                validateLogin();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

    }
      public void yanzhengma(){
          if(IsMail.isEmail(mailboxTextField.getText().toString())&& CheckEmail.checkemail(mailboxTextField.getText().toString()))
          {   sendbutton.setDisable(true);
              SecurityCode securityCode=new SecurityCode(this);
              securityCode.start();
                mailboxlabel.setText("邮箱有效！");
              String s= RandomStringUtils.randomNumeric(6);
              content=RandomStringUtils.randomAlphabetic(6);
              System.out.println("邮箱验证码："+content);
              String address=mailboxTextField.getText().toString();
              boolean b = EmailService.emailservice(content,address);
              System.out.println("发送"+(b?"成功":"失败"));

          }
          else{
                mailboxlabel.setText("邮箱无效或已存\n在！");
          }

      }
      public void test1(int time){
             yanzheng.setText("重新发送还需等待"+"("+time+")"+"秒");
      }
      public void test2()
      {
             yanzheng.setText("点击重新发送验证码");
             sendbutton.setDisable(false);
      }
    public void validateLogin() throws IllegalAccessException {
        SnowFlake a=new SnowFlake(1,2);
        long b=a.getNextID();
        String username=Long.toString(b%100000000);
//        usernamelabel.setText("您的账号ID为："+username);
        System.out.println("账号"+username);
        User user=new User();
        user.setNickname(nicknameTextField.getText().toString());
        user.setUsername(username);
        user.setPassword(Password);
        String birthday=borndate.getValue().toString();
        user.setBorndate(Date.valueOf(birthday));
        user.setSex(Sex);
        user.setMailbox(mailboxTextField.getText().toString());
        UserClientService.registerUser(user);
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText("恭喜");
        alert.setContentText("注册成功！\n您的账号ID是："+username);
        alert.showAndWait();
//        JOptionPane.showMessageDialog(null, "注册成功！\n您的账号ID是："+username);
        Stage stage=(Stage) malebutton.getScene().getWindow();
        stage.close();
        try {
            FXMLLoader fxmlLoader = new FXMLLoader();
            fxmlLoader.setLocation(getClass().getResource("register.fxml"));
            Parent root = fxmlLoader.load();
            Stage regitsterstage=new Stage();
            Scene scene = new Scene(root, 600, 730);
            regitsterstage.initStyle(StageStyle.TRANSPARENT);
            MouseFollow in = new MouseFollow(root, regitsterstage);
            regitsterstage.setScene(scene);
            regitsterstage.show();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
